import React from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import {Link} from 'dva/router';
import {Button,Row,Col,Layout, Modal, Breadcrumb,Select,Icon,Form,Input,Affix,DatePicker,message,Upload,Cascader} from 'antd';
import reqwest from 'reqwest';
import aStyle from '../styles/App.less'
import style from '../styles/ResetInput.less';
import inStyle from '../styles/Info.less'
import {numvail,selectvail,mathvail} from '../utils/Validator.js'
import {disabledStartDate,disabledEndDate} from '../utils/Date.js'
import {beforeUpload} from '../utils/BeforeUpLoad.js'
import {role_case} from '../models/Role.js';
// import CityPick from '../components/CityPick.js';
import options from '../models/CityData.js';
// import UpLoadGroup from '../components/UpLoadGroup.js';
const FormItem = Form.Item;
const Option =Select.Option;

class Setting extends React.Component{
	constructor(props){
		super(props);
		// this.edit=this.props.location.query.initv=='无敌'?JSON.parse(sessionStorage['edit']):null;
		this.state={
	    list:[],
	    set:JSON.parse(window.localStorage['setting']),
	    previewVisible: false,
      previewImage: '',
	    fileList:[],
		}
	}
	getBase64(img, callback) {
  		const reader = new FileReader();
  		reader.addEventListener('load', () => callback(reader.result));
  		reader.readAsDataURL(img);
	}
  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
	handleSubmit(e){
    e.preventDefault();
		console.log(this.state.fileList)

    this.props.form.validateFields((err, values) => {
      console.log(values);
      if (!err) {
        this.loadServer({name:values.name})
      }else{
        message.warning('请输出必填项');
      }
    });
	}
	handleChange(obj){
		console.log([obj.file])
  	switch(obj.file.status){
	    case 'uploading':
	      this.setState({fileList:obj.fileList});
	    break;
	    case 'error':
	       this.setState({fileList:[obj.file]});
	    break;
	    case 'removed':
	      this.setState({fileList:obj.fileList});
	    break;
	    default : console.log(1)
	    break;
  	}   
	}
	componentWillMount(){
		console.log(sessionStorage['edit']);
    let ava =JSON.parse(window.localStorage['setting']).avatar_url==null?require("../assets/avatar.jpg"):JSON.parse(window.localStorage['setting']).avatar_url

		this.setState({
			fileList:[{uid: -1,
      name: 'xxx.jpg',
      url:ava}]
		})
	}
	loadServer (params = {}) {
    // console.log('params:', params);
    let _data=[];
    const {province,city,area,fileList,set} = this.state;
    // console.log(fileList[0].thumbUrl)
    let _this = this;
    // return
    let avatar = fileList[0].thumbUrl==null||fileList[0].thumbUrl==undefined?{name:params.name}:{name:params.name,avatar:fileList[0].thumbUrl};
    reqwest({
      url: window.host+'/api/users/update_me',
      method: 'post',
      crossOrigin: true,
      data: {
        access_token:localStorage['token'],
        user:avatar
      },
      type: 'json',
    }).then((data) => {
      if(data.status=='success'){
        let set ={"mobile":data.current_user.mobile,"avatar":data.current_user.avatar,"avatar_url":data.current_user.avatar_url,"name":data.current_user.name,"role":data.current_user.role,"accout_name":data.current_user.account.name,"invit_url":data.current_user.account.invit_url};
      	message.success('更新成功', 1.5,()=>{
      		window.localStorage['setting']=JSON.stringify(set);
     		window.location.hash='/app/home?current=1';
      	});
      }else{
      	message.error(data.msg)
      }
    }).fail( (err, msg) =>{
       console.log(1)
    })
  }
	render(){
		const {startValue,endValue,endOpen,list,option} = this.state;
		// console.log(startValue)
		const formItemLayout = {
      labelCol: { span: 7},
      wrapperCol: { span: 17 },
      style:{minWidth:200}
    };
    const uploadButton = (
      <Row type="flex" justify="space-around" align="middle" style={{height:'100%'}}>
      <div style={{color:'#bbbbbb',marginTop:-8}}>
        <Icon type="cloud-upload-o" style={{fontSize:54}} spin={false}/>
        <h3 className="ant-upload-text" style={{fontSize:15}}>点击上传</h3>
      </div>
      </Row>
    );
  	const {getFieldDecorator}=this.props.form;
		return(
			<Layout style={{background:'#fff'}}>
				<Form className={`${inStyle.ncc_left_layout}`} onSubmit={this.handleSubmit.bind(this)}>
					<Row>
						<Breadcrumb style={{ height:60,lineHeight:'60px',fontSize:14,marginTop:20}}>
              <Breadcrumb.Item>个人设置</Breadcrumb.Item>
	       		</Breadcrumb>
	       	</Row>
       		<Row >
       			<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >

							<FormItem {...formItemLayout}  label='头像'>
								{getFieldDecorator('theme',{
								})(
  									<Upload
						          className="avatar-uploader"
						          beforeUpload={beforeUpload}
						          action="https://www.salesgj.com"
						          listType="picture-card"
						          fileList={this.state.fileList}
						          onPreview={this.handlePreview.bind(this)}
						          onChange={this.handleChange.bind(this)}
						          showUploadList={{showRemoveIcon: true }}
						          onRemove={(e,b)=>{Promise}}
						        >
						          {this.state.fileList.length > 0 ?null: uploadButton}
						        </Upload>
								)}
							</FormItem>
						</Col>
					</Row>
       		<Row >
	       		<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem {...formItemLayout}  label='姓名'>
								{getFieldDecorator('name',{
									initialValue:this.state.set.name,
									rules:[{required:true,message:'请输入你的姓名'}]
								})(
									<Input className={`${style.ncc_reset_input}`} placeholder='姓名' />
								)}
							</FormItem>
						</Col>
					</Row>
       		<Row >
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem  {...formItemLayout}  label='手机'>
								{getFieldDecorator('store',{
								})(
									<span>{this.state.set.mobile}</span>
								)}
							</FormItem>
						</Col>
					</Row>
       		<Row >
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem   {...formItemLayout}  label='角色'>
								{getFieldDecorator('store',{
								})(
									<span>{role_case[this.state.set.role]}</span>
								)}
							</FormItem>
						</Col>
					</Row>

       		<FormItem>
	       		<Affix >
	            <Button htmlType="submit" type="primary" >
	              保存
	            </Button>
	          </Affix>
          </FormItem>
				</Form>
				<Modal visible={this.state.previewVisible} footer={null} onCancel={this.handleCancel.bind(this)}>
          <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
        </Modal>
			</Layout>
		)
	}
}

const SettingForm = Form.create()(Setting);

export default connect()(SettingForm);